package sms

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"longmen/server/config/global"
	"longmen/server/pkg/db/redis/cache"
)

func newQcloud() (SMS, error) {
	configPri := cache.GetConfigPri()
	credential := common.NewCredential(
		configPri.QsmsSecretid,
		configPri.QsmsSecretkey,
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.ReqMethod = "POST"
	cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
	cpf.SignMethod = "HmacSHA1"
	client, err := sms.NewClient(credential, "ap-guangzhou", cpf)
	if err != nil {
		return nil, err
	}
	return &qcloud{client: client}, nil
}

type qcloud struct {
	client *sms.Client
}

func (a *qcloud) Name() string {
	return "qcloud-sms"
}

func (a *qcloud) SendCode(areaCode string, phoneNumber string, verifyCode string) error {
	configPri := cache.GetConfigPri()
	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = tea.String(configPri.QsmsAppid)
	request.SignName = tea.String(configPri.QsmsSign)
	request.SenderId = common.StringPtr("")
	request.SessionContext = common.StringPtr(verifyCode)
	request.TemplateParamSet = common.StringPtrs([]string{verifyCode})
	request.TemplateId = common.StringPtr(configPri.QsmsTplid)
	fullMobile := fmt.Sprintf("+%s%s", areaCode, phoneNumber)
	request.PhoneNumberSet = common.StringPtrs([]string{fullMobile})
	rs, err := a.client.SendSms(request)
	if err != nil {
		global.Log.Errorf("SendCode err:", err, "Response:", rs.ToJsonString())
		return err
	}
	return nil
}
